import CryptoJS from "crypto-js";
import { Message } from "element-ui";

export default {
    //加密
    encrypt(word, keyStr) {
        keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
        var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
        var srcs = CryptoJS.enc.Utf8.parse(word);
        var encrypted = CryptoJS.AES.encrypt(srcs, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return encrypted.toString();
    },
    //解密
    decrypt(word, keyStr) {
        keyStr = keyStr ? keyStr : "abcdefgabcdefg12";
        var key = CryptoJS.enc.Utf8.parse(keyStr); //Latin1 w8m31+Yy/Nw6thPsMpO5fg==
        var decrypt = CryptoJS.AES.decrypt(word, key, {
            mode: CryptoJS.mode.ECB,
            padding: CryptoJS.pad.Pkcs7
        });
        return CryptoJS.enc.Utf8.stringify(decrypt).toString();
    },
    // MD5加密工具
    myMd5(word) {
        return CryptoJS.MD5(word).toString();
    },
    /**
     * 创建唯一的字符串
     * @return {string} ojgdvbvaua40
     */
    createUniqueString() {
        const timestamp = +new Date() + "";
        const randomNum = parseInt((1 + Math.random()) * 65536) + "";
        return (+(randomNum + timestamp)).toString(32);
    },

    /**
     * 数字存储大小格式化
     * @param {number} num 存储大小 单位：Byte
     * @param {number} digits 保留几位小数
     * @return {string} 2MB
     */
    toStorage(num, digits) {
        digits = digits || 2;
        if (num < 1024) {
            return num + "B";
        }
        num = (num * 1000) / 1024;
        const si = [
            { value: 1e18, symbol: "E" },
            { value: 1e15, symbol: "P" },
            { value: 1e12, symbol: "T" },
            { value: 1e9, symbol: "G" },
            { value: 1e6, symbol: "M" },
            { value: 1e3, symbol: "K" }
        ];
        for (let i = 0; i < si.length; i++) {
            if (num >= si[i].value) {
                return (
                    (num / si[i].value)
                        .toFixed(digits)
                        .replace(/\.0+$|(\.[0-9]*[1-9])0+$/, "$1") +
                    si[i].symbol +
                    "B"
                );
            }
        }
    },

    /**
     * 图片上传
     * @param {file} file el-upload文件对象
     * @param {number} size 限制的文件大小(kb) 默认10M
     */
    validImgUpload(file, size) {
        size = +size || 10240;
        const isSizeOut = file.size / 1024 > size;
        if (isSizeOut) {
            Message.error("上传图片大小不能超过" + this.toStorage(size * 1024));
        }
        return !isSizeOut;
    },
};
